﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//using System.Configuration;
//using System.Data.SqlClient;

using ECS.Framework;
using ECS.DAL;
using ECS.DAL.Component;
using ECS.DAL.Entity;

namespace E_ICS.E_ICS
{
    public partial class d : Form
    {
        #region private properties
        private Main.frmMain2 _mainForm = null;
        
        private string comment_type_id = string.Empty;
        private string comment_id = string.Empty;
        private string comment_name = string.Empty;
        private string value = string.Empty;
        private bool _isLoadedData = false;
        private CommentRecordComponent _commentComp = null;
        private List<ObjectContext> _dataList = new List<ObjectContext>();
        private SortableBindingList<CommentRecord> _gridSource = new SortableBindingList<CommentRecord>();
        private List<ObjectContext> _deleteList = new List<ObjectContext>();

        //private int countpass = 0;
        //private int allpass = 0;
        //private SqlConnection sqlCon = null;
        //private DataSet datasetInsert = null;
        //private DataSet datasetUpdate = null;
        //private DataSet dtOtherinfo = null;
        #endregion

        #region form events
        
        public d(Main.frmMain2 paramMain)
        {
            InitializeComponent();
            _mainForm = paramMain;
        }
        /// <summary>
        /// close form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                this.Close();
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }
        /// <summary>
        /// add new data
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                GlobalVariable.flagfromfrmAddOtherInfo = 1;
                frmAddOtherInfo aoi = new frmAddOtherInfo(_mainForm);
                if (aoi.ShowDialog() == DialogResult.Yes)
                {
                    getDataFromAddOtherInfo();
                }
            }
            catch (Exception ex)
            {
               // CommonMessageBox.ShowMessageError(ex);
            }
        }

        private void frmEditOtherInfo_Load(object sender, EventArgs e)
        {
            SetScreen();
            string connString = string.Empty;
            try
            {
                //connString = ConfigurationManager.ConnectionStrings["con3"].ConnectionString;
                //sqlCon = new SqlConnection(connString);
                _commentComp = new CommentRecordComponent();
                showdgvfrmEditOtherInfo();
                setRowNumber(dgvOtherinfo);
                _isLoadedData = true;
                dgvOtherinfo.RowHeadersWidth = 60;
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
            
        }
         private void SetScreen()
        {
            this.Text = CommonResourceString.GetResourseValue("scn_EditOtherInfo");
            btnSave.Text = CommonResourceString.GetResourseValue("scn_EditOtherInfo_btnSave");
            btnAdd.Text = CommonResourceString.GetResourseValue("scn_EditOtherInfo_btnAdd");
            btnClose.Text = CommonResourceString.GetResourseValue("scn_EditOtherInfo_btnCancel");
            
                  
          
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            DialogResult result = System.Windows.Forms.DialogResult.No;
            try
            {
                result = CheckSaveChanged();
                if (result == System.Windows.Forms.DialogResult.Yes || result == System.Windows.Forms.DialogResult.No)
                {
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }
        private void frmEditOtherInfo_FormClosing(object sender, FormClosingEventArgs e)
        {

        }
        private void dgvOtherinfo_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                //if (_gridSource.Count > 0)
                //{
                //    if (e.ColumnIndex == dgvOtherinfo.Columns["btnDelete"].Index && e.RowIndex >= 0)    // Delete Dim
                //    {
                //        if (_gridSource[e.RowIndex].GetObjectSate() != OBJECT_STATE.Insert)
                            //{
                            //    CommentRecord obj = _gridSource[e.RowIndex];
                            //    obj.AppId = GlobalVariable.user.ApplicationID;
                            //    obj.UserId = GlobalVariable.user.UserID;
                            //    obj.Device = GlobalVariable.user.Device;
                            //    obj.DeleteObject();
                            //    _dataComponent.Delete((ObjectContext)_gridSource[e.RowIndex]);
                            //}
                            //_gridSource.RemoveAt(e.RowIndex);
                            //setRowNumber((DataGridView)sender);
                //    }
                //}
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvOtherinfo_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            try
            {
                if (_isLoadedData)
                {
                    DataGridView dgv = (DataGridView)sender;
                    if (dgv.Rows.Count > 0)
                    {
                        //kung
                        setRowNumber(dgvOtherinfo);
                        dgv.Rows[e.RowIndex].HeaderCell.Value = String.Format("{0}", e.RowIndex +1);
                    }
                }
            }
            catch (Exception ex)
            {
               //CommonMessageBox.ShowMessageError(ex);
            }
        }
        #endregion

        #region private methods
        
        public void showdgvfrmEditOtherInfo()
        {
            CommentRecord condition = new CommentRecord();
            condition.SlipId = ViewEditWeightSlip.slip_id;
            _dataList = _commentComp.Search(condition);
            foreach (ObjectContext item in _dataList)
            {
                 _gridSource.Add((CommentRecord)item);
            }
            dgvOtherinfo.AutoGenerateColumns = false;
            dgvOtherinfo.Columns.Add("CommentNumber", "Comment Number");
            dgvOtherinfo.Columns[0].Visible = false;
            dgvOtherinfo.Columns[0].ReadOnly = true;
            dgvOtherinfo.Columns[0].DataPropertyName = "CommentNumber"; //condition.CommentNumber

            dgvOtherinfo.Columns.Add("CommentType", "Comment Type");
            dgvOtherinfo.Columns[1].DataPropertyName = "CommentTypeName"; //condition.CommentTypeName
            dgvOtherinfo.Columns.Add("CommentValue", "Value");
            dgvOtherinfo.Columns[2].DataPropertyName = "Value"; //condition.Value
            //DataGridViewButtonColumn btndel = new DataGridViewButtonColumn();
            //btndel.HeaderText = "Delete";
            //btndel.Text = "Delete";
            //btndel.Name = "btnDelete";
            //btndel.UseColumnTextForButtonValue = true;
            //dgvOtherinfo.Columns.Add(btndel);

            dgvOtherinfo.DataSource = _gridSource;

            //SqlCommand cmd = new SqlCommand("select cm.comment_type_id,cm.comment_id,ct.comment_name,cm.[value] from t_eics_comment cm join t_eics_comment_type ct on ct.comment_type_id=cm.comment_type_id  where cm.slip_id=@slip_id order by cm.create_date", sqlCon);
            //cmd.Parameters.AddWithValue("@slip_id", ViewEditWeightSlip.slip_id);
            ////cmd.Parameters.AddWithValue("@mawb_id", MAWB_id);
            //sqlCon.Open();

            //SqlDataAdapter daOtherinfo = new SqlDataAdapter(cmd);
            //dtOtherinfo = new DataSet();
            //daOtherinfo.Fill(dtOtherinfo, "dtOtherinfo");
            //DataTable dtOtherinfo_TB = CreateOtherInfo_TB(dtOtherinfo);
            //dgvOtherinfo.DataSource = dtOtherinfo_TB;

            //sqlCon.Close();
            //dgvOtherinfo.Columns[0].Visible = false;
            //dgvOtherinfo.Columns[1].Visible = false;
        }

        //DataTable TOtherinfo = new DataTable();

        //private DataTable CreateOtherInfo_TB(DataSet ds)
        //{
        //    TOtherinfo = new DataTable();
        //    ///////////create head column/////////////////
         
        //    TOtherinfo.Columns.Add("comment_type_id", typeof(string));
        //    TOtherinfo.Columns.Add("comment_id", typeof(string));
        //    TOtherinfo.Columns.Add("Data Key", typeof(string));
        //    TOtherinfo.Columns.Add("Data Value", typeof(string));

        //    ///////////////////////////////////////////////
        //    int row = dtOtherinfo.Tables[0].Rows.Count;
        //    for (int i = 0; i < row; i++)
        //    {
        //        comment_type_id = dtOtherinfo.Tables[0].Rows[i]["comment_type_id"].ToString().Trim();
        //        comment_id = dtOtherinfo.Tables[0].Rows[i]["comment_id"].ToString().Trim();
        //        comment_name = dtOtherinfo.Tables[0].Rows[i]["comment_name"].ToString().Trim();
        //        value = dtOtherinfo.Tables[0].Rows[i]["value"].ToString().Trim();

        //        TOtherinfo.Rows.Add(comment_id, comment_type_id, comment_name, value);
        //    }
        //    return TOtherinfo;
        //}

        public void getDataFromAddOtherInfo()
        {
            //// TOtherinfo.Clear();
            //// dgvOtherinfo.DataSource = TOtherinfo;

            //TOtherinfo.Rows.Add("", ViewEditComment.Data_Key_id, ViewEditComment.Data_Key, ViewEditComment.Data_Value);
            //dgvOtherinfo.Refresh();
            //setRowNumber(dgvOtherinfo);
            CommentRecord newItem = new CommentRecord();
            newItem.SlipId = ViewEditWeightSlip.slip_id;
            newItem.CommentNumber = _gridSource.Count + 1;
            newItem.CommentTypeId = ViewEditComment.Data_Key_id;
            newItem.CommentTypeName = ViewEditComment.Data_Key;
            newItem.Value = ViewEditComment.Data_Value;
            _gridSource.Add(newItem);
            setRowNumber(dgvOtherinfo);
        }
        private void setRowNumber(DataGridView dgv)
        {
            // dgvWeight_Disp.
            //dgv.RowHeadersWidth = 100;
            //dgvWeight_Disp.Columns[-1].HeaderText = "No";

            foreach (DataGridViewRow row in dgv.Rows)
            {
                //if (row.Index == dgv.Rows.Count - 1)
                //{
                //    row.HeaderCell.Value = "";
                //}
                //else
                {
                    row.HeaderCell.Value = String.Format("{0}", row.Index + 1);
                }
            }
        }
        private DialogResult CheckSaveChanged()
        {
            DialogResult result = System.Windows.Forms.DialogResult.No;
            bool isModified = false;
            for (int i = 0; i < _gridSource.Count; i++)
            {
                if (_gridSource[i].GetObjectSate() != OBJECT_STATE.None)
                {
                    isModified = true;
                    _gridSource[i].Device = GlobalVariable.user.Device;
                    _gridSource[i].AppId = GlobalVariable.user.ApplicationID;
                    _gridSource[i].UserId = GlobalVariable.user.UserID;
                    _gridSource[i].SlipId = ViewEditWeightSlip.slip_id;
                }
            }
            if (isModified)
            {
                result = CommonMessageBox.displayConfirmSave();
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    _commentComp.SaveChanges(_gridSource.ToList<ObjectContext>());
                }
                
            }
            return result;

            //#region old code
            //countpass = 0;
            //for (int i = 0; i < dgvOtherinfo.Rows.Count - 1; i++)
            //{
                

            //    allpass = dgvOtherinfo.Rows.Count - 1;
            //    string dim_id = dgvOtherinfo.Rows[i].Cells[0].Value.ToString();
            //    //ถ้า dim_id = null แสดงว่า insert เป็นค่าใหม่
            //    if (dim_id.Equals(""))
            //    {

            //        try
            //        {
            //            SqlCommand cmd = new SqlCommand();
            //            cmd.CommandText = "usp_InsertCommentRecord";
            //            cmd.CommandType = CommandType.StoredProcedure;
            //            cmd.Connection = sqlCon;
            //            cmd.Parameters.AddWithValue("@in_vchApplicationID", GlobalVariable.user.ApplicationID);
            //            cmd.Parameters.AddWithValue("@in_vchSlipID", ViewEditWeightSlip.slip_id);
            //            cmd.Parameters.AddWithValue("@in_intCommentNumber", i + 1);
            //            cmd.Parameters.AddWithValue("@in_vchCommentTypeID", dgvOtherinfo.Rows[i].Cells[1].Value);
            //            cmd.Parameters.AddWithValue("@in_vchValue", dgvOtherinfo.Rows[i].Cells[3].Value);

            //            cmd.Parameters.AddWithValue("@in_vchDevice", GlobalVariable.user.Device);
            //            cmd.Parameters.AddWithValue("@in_vchUserID", GlobalVariable.userName);

            //            sqlCon.Open();
            //            SqlDataAdapter da = new SqlDataAdapter(cmd);
            //            datasetInsert = new DataSet();
            //            da.Fill(datasetInsert, "InsertDimensionRecord");
            //            string status = datasetInsert.Tables[0].Rows[0]["Status"].ToString();
            //            string Messagest = datasetInsert.Tables[0].Rows[0]["Message"].ToString();
            //            if (status == "PASS")
            //            {
            //                countpass = countpass + 1;
            //            }
            //            else
            //            {
            //                MessageBox.Show(Messagest);
            //            }
            //            sqlCon.Close();
            //        }
            //        catch (Exception objEx)
            //        {
            //            //sqlCon.Close();
            //            //string str = objEx.Message;
            //            //MessageBox.Show(str);
            //            CommonMessageBox.ShowMessageError(objEx);
            //        }
            //    }

            //        //เคสอัพเดท(มีค่า dim_id มา
            //    else
            //    {
            //        try
            //        {
            //            SqlCommand cmd = new SqlCommand();
            //            cmd.CommandText = "usp_UpdateCommentRecord";
            //            cmd.CommandType = CommandType.StoredProcedure;
            //            cmd.Connection = sqlCon;
            //            cmd.Parameters.AddWithValue("@in_vchApplicationID", GlobalVariable.user.ApplicationID);
            //            cmd.Parameters.AddWithValue("@in_vchSlipID", ViewEditWeightSlip.slip_id);
            //            cmd.Parameters.AddWithValue("@in_intCommentNumber", i + 1);
            //            cmd.Parameters.AddWithValue("@in_vchCommentID", dgvOtherinfo.Rows[i].Cells[0].Value);
            //            cmd.Parameters.AddWithValue("@in_vchCommentTypeID", dgvOtherinfo.Rows[i].Cells[1].Value);
            //            cmd.Parameters.AddWithValue("@in_vchValue", dgvOtherinfo.Rows[i].Cells[3].Value);

            //            cmd.Parameters.AddWithValue("@in_vchDevice", GlobalVariable.user.Device);
            //            cmd.Parameters.AddWithValue("@in_vchUserID", GlobalVariable.userName);

            //            sqlCon.Open();
            //            SqlDataAdapter da = new SqlDataAdapter(cmd);
            //            datasetUpdate = new DataSet();
            //            da.Fill(datasetUpdate, "UpdateDimensionRecord");
            //            string status = datasetUpdate.Tables[0].Rows[0]["Status"].ToString();
            //            string Messagest = datasetUpdate.Tables[0].Rows[0]["Message"].ToString();
            //            if (status == "PASS")
            //            {
            //                countpass = countpass + 1;
            //            }
            //            else
            //            {
            //                CommonMessageBox.ShowMessageWarning(Messagest);
            //            }
            //        }
            //        catch (Exception objEx)
            //        {
            //            CommonMessageBox.ShowMessageError(objEx);

            //        }
            //        finally
            //        {
            //            if (sqlCon != null && sqlCon.State == ConnectionState.Open)
            //            {
            //                sqlCon.Close();
            //            }
            //        }
            //    }
                
            //}
            //if (countpass == allpass)
            //{
            //    this.Close();
            //}

            //// showdgvOtherinfoDisplay();
            //#endregion
        }


        
        #endregion

    }
}
